package com.fulihui.wgj.schedule.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.weixinsdk.WeixinSDK;
import com.fulihui.weixinsdk.request.news.NewsArticletotalRequest;
import com.fulihui.weixinsdk.result.news.NewsStatDetailList;
import com.fulihui.weixinsdk.result.news.NewsStatDetails;
import com.fulihui.weixinsdk.result.news.NewsStatResult;
import com.fulihui.wgj.datastatis.facade.api.mass.MassDataStatisApi;
import com.fulihui.wgj.datastatis.facade.request.ArticleTotalStatDetailRequest;
import com.fulihui.wgj.datastatis.facade.request.ArticleTotalStatRequest;
import com.fulihui.wgj.facade.dto.WxPlatformDTO;
import com.fulihui.wgj.facade.service.platform.WxPlatformService;
import com.fulihui.wgj.schedule.annotation.MutexLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: Levon
 * @date: 2018-08-20 09:58
 */
@Component
public class MassDataStatJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(MassDataStatJob.class);

    @Autowired
    private WeixinSDK weixinSDK;

    @Reference(version = "1.0.0")
    private MassDataStatisApi massDataStatisApi;

    @Reference(version = "1.0.0")
    private WxPlatformService wxPlatformService;

    @MutexLock(node = "${job.node.massDataStatJob}")
    @Scheduled(cron = "${job.cron.massDataStatJob}")
    public void excute() {

        Date now = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        String refDate = DateUtils.formatWebFormat(cal.getTime());

        SimpleResult<List<WxPlatformDTO>> result = wxPlatformService.queryUsefulPlatform();
        List<WxPlatformDTO> resultData = result.getData();
        if (!CollectionUtils.isEmpty(resultData)) {
            for (WxPlatformDTO platform : resultData) {
                String appId = platform.getAppId();
                String accessToken = null;
                SimpleResult<String> tokenResult = wxPlatformService.queryTokenFromRedis(appId);
                if (RpcResultCheckUtil.isSuccess(tokenResult)) {
                    accessToken = tokenResult.getData();
                }
                NewsArticletotalRequest newsArticletotalRequest = new NewsArticletotalRequest();
                newsArticletotalRequest.setAccess_token(accessToken);
                newsArticletotalRequest.setBegin_date(refDate);
                newsArticletotalRequest.setEnd_date(refDate);
                NewsStatResult newsStatResult = weixinSDK.invokeService(newsArticletotalRequest);
                if (!newsStatResult.isSuccess()) {
                    LOGGER.info("{}未找到统计记录", appId);
                    continue;
                }

                List<NewsStatDetailList> statDetailLists = newsStatResult.getList();
                if (CollectionUtils.isEmpty(statDetailLists)) {
                    LOGGER.info("{}未找到统计记录,统计数据为空", appId);
                    continue;
                }

                for (NewsStatDetailList statDetailList : statDetailLists) {
                    ArticleTotalStatRequest request = new ArticleTotalStatRequest();
                    request.setAppid(appId);
                    request.setMsgid(statDetailList.getMsgid());
                    request.setRefDate(statDetailList.getRef_date());
                    request.setTitle(statDetailList.getTitle());
                    BaseResult baseResult = massDataStatisApi.saveArticleTotalStat(request);
                    if (!RpcResultCheckUtil.isSuccess(baseResult)) {
                        LOGGER.info("{}没有统计数据，msgid={}", appId, statDetailList.getMsgid());
                        continue;
                    }

                    List<NewsStatDetails> details = statDetailList.getDetails();
                    if (!CollectionUtils.isEmpty(details)) {
                        for (NewsStatDetails detail : details) {
                            ArticleTotalStatDetailRequest detailRequest = new ArticleTotalStatDetailRequest();
                            String jsonDetail = JSON.toJSONString(detail);
                            detailRequest.setAppid(appId);
                            detailRequest.setDetails(jsonDetail);
                            detailRequest.setMsgid(statDetailList.getMsgid());
                            massDataStatisApi.saveArticleTotalStatDetail(detailRequest);
                        }
                    }
                }
            }
        }
    }
}
